package com.tbi.graphcolouring.testers;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

import com.tbi.algorithm.datacollector.IStopperDataCollector;
import com.tbi.graphcolouring.datacollector.AlgorithmStopDataCollector;

public class PlotPanel {
	
	private PlotPanel() { }
	
	public static ChartPanel getInstance(IStopperDataCollector dataCollector){
		PlotPanel pp2 = new PlotPanel();
		XYDataset dataset = pp2.createDataset(dataCollector);
		JFreeChart chart = pp2.createChart(dataset);
		return new ChartPanel(chart);
	}

	private JFreeChart createChart(XYDataset dataset) {
		JFreeChart chart = ChartFactory.createXYLineChart(
				"Genethic algorithm overview",
				"Population",
				"Rating",
				dataset,
				PlotOrientation.VERTICAL,
				true,
				true,
				false
				);
		return chart;
	}

	private XYDataset createDataset(IStopperDataCollector dataCollector) {
		XYSeriesCollection dataset = new XYSeriesCollection();
		
		if(dataCollector != null){
			AlgorithmStopDataCollector data = (AlgorithmStopDataCollector) dataCollector;
			
			XYSeries worst = new XYSeries("Worst");
			XYSeries best = new XYSeries("Best");
			XYSeries average = new XYSeries("Average");
			
			for(int i=0; i<data.getGenerations(); i++){
				worst.add(i, data.getWorstEntity(i).rating);
				average.add(i, data.getAverageEntity(i));
				best.add(i, data.getBestEntity(i).rating);
			}
			
			dataset.addSeries(worst);
			dataset.addSeries(best);
			dataset.addSeries(average);
		}
		
		return dataset;
	}
}
